import asyncio
from app import app
import re
from pyrogram import filters, Client
from pyrogram.types.messages_and_media import Message
from filters import custom_filters
from config import GROUP_ID,my_id,auto_choujiang,target_group,my_ptid,prize_list,start_time1,start_time2, end_time1,end_time2
from random import randint,random
from datetime import datetime
from app.libs import others
from app.libs.logs import logger


lottery_list = {}

#################抽奖监听#######################
@app.on_message(
    custom_filters.choujiang_bot
    & filters.regex(r"^新的抽奖已经创建[\s\S]+参与关键词：「(.+)」")
)
async def lottery_forword_message(client:Client, message:Message):

    lottery_info = {}


    await others.sendmessage(GROUP_ID["PRIVATE_ID"],f"{message.text}\n\n{message.link}")
    #await app.forward_messages(chat_id="me",from_chat_id=message.chat.id,message_ids=[message.id])
    nowtime =await others.get_nowtime('time')
    start_time1_1 = datetime.strptime(start_time1, '%H:%M:%S%z')
    start_time2_1 = datetime.strptime(start_time2, '%H:%M:%S%z')
    end_time1_1 = datetime.strptime(end_time1, '%H:%M:%S%z')
    end_time2_1 = datetime.strptime(end_time2, '%H:%M:%S%z')
    
    pattern = {"ID": r"抽奖 ID：(.+)",
               "boss_name": r"创建者：(/w+)",
               "boss_ID": r"创建者：[\s\S]+(/d+)",
               "prize": r"奖品：\n      ▸ (.+)",
               "allowuser": r"允许普通用户参加：(.+)",
               "keyword": r"参与关键词：「(.+)」",
               }                
    for key, pat in pattern.items():
        match = re.search(pat, message.text)
        lottery_info[key] = match.group(1) if match else ""
    result_key= await prize_check(lottery_info["prize"])

    if auto_choujiang:
        if ((nowtime > start_time1_1.time()
             and nowtime < start_time2_1.time())
             or (nowtime > end_time1_1.time()
                 and nowtime < end_time2_1.time())):            
            if message.chat.id in target_group: 
                if result_key:
                    logger.info(f"自动抽奖已经打开,且符合自动抽奖时间,且属于目标群组范围，且奖品符合设定范围 开始自动抽奖 抽奖ID: {lottery_info['ID']}")
                    lottery_list[lottery_info['ID']] = {'keyword':lottery_info['keyword'],'boss_name':lottery_info['boss_name'],'boss_ID':lottery_info['boss_ID'],'ptsite':result_key,'prizechat':message.chat.id,'flag':0}
                    await asyncio.sleep(randint(20, 120)) 
                    if lottery_info['ID'] in lottery_list:
                        logger.info(f"ID: {lottery_info['ID']}的抽奖,随机等待后未结束，故参与抽奖,参与群组:{message.chat.id},抽奖关键字:{lottery_list[lottery_info['ID']]['keyword']}")
                        re_message = await app.send_message(message.chat.id, lottery_list[lottery_info['ID']]['keyword'])
                        lottery_list[lottery_info['ID']]['flag'] = 1
                    else:
                        logger.info(f"ID: {lottery_info['ID']}的抽奖，在随机等待时间内已经结束，故不参与抽奖")
                else:
                    logger.info(f"抽奖ID: {lottery_info['ID']} 其奖品不符合设定范围故不参与抽奖 ")
            else:
                logger.info(f"抽奖ID: {lottery_info['ID']} 所在群组不属于设定的目标群组范围,故不参与抽奖")
        else:
            logger.info(f"抽奖ID: {lottery_info['ID']} 不在设定自动抽奖时间内,故不参与抽奖。")


#################中奖结果监听#######################
@app.on_message(
    custom_filters.choujiang_bot
    & filters.regex(r"^参与人数够啦！！开奖[\s\S]+中奖信息\n([\s\S]+)")
)
async def lottery_forword_message(client:Client, message:Message):
    finish_key = ""
    winner = message.matches[0].group(1)
    print("lottery_list ass",lottery_list)
    if auto_choujiang:
        if message.chat.id in target_group:
            match1 = re.search(r"抽奖 ID：(.+)", message.text)
            finish_key = match1.group(1) if match1 else ""
            if str(my_id) not in str(lottery_list[finish_key]['boss_ID']):
                logger.info(f"抽奖不是自己发起的，未中奖随机发黑幕,中奖也自动领奖")
                if str(my_id) in winner:                
                    await asyncio.sleep(randint(20, 60)) 
                    if lottery_list[finish_key]['ptsite'] == "ZHQUE_ID":
                        re_message1 = await app.send_message(message.chat.id,f"感谢{lottery_list[finish_key]['boss_name']}大佬")
                        re_message2 = await app.send_message(-4200814739,f"感谢{lottery_list[finish_key]['boss_name']}大佬赏赐 我在这里")
                    elif lottery_list[finish_key]['ptsite'] == "DOLBY_ID":
                        re_message1 = await app.send_message(message.chat.id,f"感谢{lottery_list[finish_key]['boss_name']}大佬")
                        re_message2 = await app.send_message(-4200814739,f"感谢{lottery_list[finish_key]['boss_name']}大佬赏赐 我在这里")
                    else:
                        re_message1 = await app.send_message(message.chat.id,f"感谢{lottery_list[finish_key]['boss_name']}大佬, \n我的(用户名)ID是: {my_ptid}")
    
                else:
                    if lottery_list.get(finish_key):
                        if lottery_list[finish_key]['flag'] == 1:
                            await asyncio.sleep(randint(5, 15)) 
                            if random(0, 1) > 0.45:
                                logger.info(f"随机概率中标,发送未中奖黑幕")
                                re_message1 = await app.send_message(message.chat.id,f"强烈反对黑幕")
                            else:
                                logger.info(f"随机概率未中标,不发送未中奖黑幕")
            else:
                logger.info(f"抽奖是自己发起的，故不发黑幕,中奖也不领奖")


            if lottery_list.get(finish_key):
                del lottery_list[finish_key]  
            print("lottery_list aftter",lottery_list)

#################查找元素是否在字符串中存在，存咋则返回对应键####################### 
async def prize_check(prize_string):
    for key, prize_names in prize_list.items():
        for prize in prize_names:
            if prize in prize_string:
                return key
    return False
        
